package com.tjvib.view.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.kyleduo.switchbutton.SwitchButton;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.ToastUtil;
import com.tjvib.widget.ItemGroup;

public class SettingActivity extends BaseActivity {

    private ItemGroup setting_ig_hz;
    private SwitchButton setting_sb_battery, setting_sb_bluetooth;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_setting;
    }

    @Override
    protected boolean initView() {
        setting_ig_hz = findViewById(R.id.setting_ig_hz);

        setting_sb_battery = findViewById(R.id.setting_sb_battery);
        setting_sb_battery.setOnClickListener(v -> {
            ToastUtil.show("当前" + setting_sb_battery.isChecked());
        });

        setting_sb_bluetooth = findViewById(R.id.setting_sb_bluetooth);
        setting_sb_bluetooth.setOnClickListener(v -> {
            ToastUtil.show("当前" + setting_sb_bluetooth.isChecked());
        });

        return true;
    }

    @Override
    protected boolean initData() {
        setting_ig_hz.setItem_group_et_con("123456");
        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }


    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    //判断是否要收起键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    //隐藏软键盘并让editText失去焦点
    private void hideKeyboard(IBinder token) {
        setting_ig_hz.clearFocus();
        ToastUtil.show("用户名修改成功");
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}